package com.general.framework.core.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leejean
 * @ClassName: ThreadContext
 * @Description: 线程上下文
 * @date 2020年07月01 19:08:02
 */
public class ThreadContext {

    private static final ThreadLocal<Map<Object, Object>> resources = new InheritableThreadLocalMap<>();

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public static Object getValue(Object key) {
        Map<Object, Object> perThreadResources = resources.get();
        final Object value = perThreadResources != null ? perThreadResources.get(key) : null;
        return value;
    }

    /**
     * 设置值
     *
     * @param key
     * @param value
     */
    public static void putValue(Object key, Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        if (value == null) {
            removeValue(key);
            return;
        }
        ensureResourcesInitialized();
        resources.get().put(key, value);
    }

    /**
     * 移除值
     *
     * @param key
     * @return
     */
    public static Object removeValue(Object key) {
        Map<Object, Object> perThreadResources = resources.get();
        Object value = perThreadResources != null ? perThreadResources.remove(key) : null;
        return value;
    }

    /**
     * 删除线程上下文
     */
    public static void remove() {
        resources.remove();
    }

    /**
     * 获取所有资源
     *
     * @return
     */
    public static Map<Object, Object> getResource() {
        ensureResourcesInitialized();
        return Collections.unmodifiableMap(resources.get());
    }

    /**
     * 判定及资源池初始化
     */
    private static void ensureResourcesInitialized() {
        if (resources.get() == null) {
            resources.set(new HashMap<>(5));
        }
    }

    /**
     * 重写子线程实现
     *
     * @param <T>
     */
    private static final class InheritableThreadLocalMap<T extends Map<Object, Object>> extends InheritableThreadLocal<Map<Object, Object>> {

        @Override
        protected Map<Object, Object> childValue(Map<Object, Object> parentValue) {
            if (parentValue != null) {
                return (Map<Object, Object>) ((HashMap<Object, Object>) parentValue).clone();
            } else {
                return null;
            }
        }
    }

}
